// user_io.cpp
#include "iostream"
#include "user_io.h"
#include <fstream>
#include <sstream>
#include "crypto.h"
#include <fstream>

void saveUsersToFile(const std::string& filename) {
    std::ofstream outfile(filename, std::ios::app);

    if (!outfile.is_open()) {
        std::cerr << "Failed to open the file for writing." << std::endl;
        return;
    }

    for (const User& user : users) {
        outfile << user.username <<" " <<  user.password << "\n";
    }

    outfile.close();
}

void loadUsersFromFile(const std::string& filename) {
    load_users.clear(); // 清空之前的用户数据

    std::ifstream infile(filename);

    if (!infile.is_open()) {
        std::cerr << "Failed to open the file for reading." << std::endl;
        return;
    }

    // 读取整个文件内容
    std::stringstream fileContent;
    fileContent << infile.rdbuf();

    // 分割文件内容，假设每个用户数据之间使用换行符分隔
    std::string userData;
    while (std::getline(fileContent, userData)) {
        // 将用户数据按照特定格式解析并添加到容器中
        std::istringstream userDataStream(userData);
        User user;
        if (userDataStream >> user.username >> user.password) {
            user.password = encryptDecrypt(user.password);
            load_users.push_back(user);
        } else {
            std::cerr << "Failed to parse user data: " << userData << std::endl;
        }
    }

    infile.close();
}

